package com.zq.it.service.impl.admin;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.zq.it.pojo.CmgTemp;
import com.zq.it.pojo.Course;
import com.zq.it.pojo.CourseManage;
import com.zq.it.service.admin.CourseManageService;
import com.zq.it.service.common.BaseServiceImpl;

public class CourseManageServiceImpl extends BaseServiceImpl
		implements
			CourseManageService {

	// private List<CmgTemp> COURSE_M_LIST; //存储查询数据

	@Override
	public void removeCourseManage(Integer id) {
		getCourseManageDao().deleteCourseManageEtyByID(id);
		// TODO Auto-generated method stub
	}

	@Override
	public void renewalCourseManage(CourseManage cmg) {
		if (cmg.getAddress().getAddressId() == null)
			cmg.setAddress(null);
		if (cmg.getTclass().getClassId() == null)
			cmg.setTclass(null);
		if (cmg.getTeacher().getTeacherId() == null)
			cmg.setTeacher(null);
		getCourseManageDao().updateCourseManageEty(cmg);
	}

	@Override
	public List getCourseManage(Integer id) {
		return getCourseManageDao().findCourseManageEtyById(id);
	}

	@Override
	public void addCourseManage(CourseManage cmg) {
		getCourseManageDao().saveCourseManageEty(cmg);
		// TODO Auto-generated method stub
	}

	@SuppressWarnings("deprecation")
	@Override
	public List getCourseManageListByType(String type, String parameter) {
		List list = null;
		if (type.equals("0"))
			list = getCourseManageDao()
					.findCourseManageEtyById(Integer.parseInt(parameter));
		if (type.equals("1"))
			list = getCourseManageDao().findCourseManageEtyByName(parameter);
		return list;
	}
	@Override
	public List getCourseManageByExmp(CourseManage courseManage) {
		// TODO Auto-generated method stub
		return getCourseManageDao().findCourseManageEtyByExmp(courseManage);
	}
	@Override
	public void removeCourseManage(CourseManage courseManage) {
		// TODO Auto-generated method stub
		getCourseManageDao().deleteCourseManageEtyByObj(courseManage);
	}

	@Override
	public List<CourseManage> importCourseManageList(File courseMAGFile) {
		List<CourseManage> courseMAGList = getAcmyListFromStr(
				importxlsxFile(courseMAGFile));
		List<CourseManage> existAcmyList = new ArrayList<CourseManage>();

		for (int i = 0; i < courseMAGList.size(); i++) {
			CourseManage courseMAG = courseMAGList.get(i);
			if (!getCourseManageDao().findCourseManageEtyById(courseMAG.getId())
					.isEmpty())
				existAcmyList.add(courseMAG);
		}
		courseMAGList.removeAll(existAcmyList);
		if (!courseMAGList.isEmpty())
			getCourseManageDao().saveCourseManageEtyList(courseMAGList);
		return existAcmyList;
	}
	private List<CourseManage> getAcmyListFromStr(String str) {
		List<CourseManage> list = new ArrayList<CourseManage>();
		String[] firstArray = str.split(";");
		for (int i = 0; i < firstArray.length; i++) {
			String[] secondArray = firstArray[i].split(":");
			CourseManage courseManage = new CourseManage();
			courseManage
					.setCourse(new Course(Integer.parseInt(secondArray[1])));
			list.add(courseManage);
		}
		return list;
	}

	// 数据的导出
	@Override
	public ByteArrayInputStream exportCourseManageList(String[] headTitle,
			List<CourseManage> list) {
		return new ByteArrayInputStream(
				exportToExcel(list, headTitle).toByteArray());
	}

	// 根据sql语句拼接查询课程安排表id,courseTimeSet,weeks,courseType,credit,fkcoruseId,fk,classId,fkaddressId,fkteacherId;
	@Override
	public List getCourseManageListBySQL(CourseManage courseManage) {
		Object obj = null; // 接收对象参数
		StringBuilder builder = new StringBuilder("select "
				+ "new com.zq.it.pojo.CmgTemp(" + "cmg.id,"
				+ "cmg.courseTimeSet," + "cmg.weeks," + "cmg.courseType,"
				+ "cmg.credit," + "t.teacherId," + "t.teacherName,"
				+ "c.courseId," + "c.courseName," + "adr.addressId,"
				+ "adr.addressName," + "tc.classId," + "tc.className)"
				+ "from CourseManage cmg" + " left join cmg.teacher t"
				+ " left join cmg.course c" + " left join cmg.address adr"
				+ " left join cmg.tclass tc" + " where 0=0\n");

		if (courseManage != null) {
			if ((obj = courseManage.getAddress().getAddressId()) != null)
				if (!obj.equals(-1))
					builder.append("and adr.addressId=" + obj);
				else
					builder.append("and adr is null");
			if ((obj = courseManage.getCourse().getCourseId()) != null)
				if (!obj.equals(-1))
					builder.append(" and c.courseId=" + obj);
				else
					builder.append(" and c is null");
			if (null != (obj = courseManage.getTeacher().getTeacherId()))
				if (!obj.equals(-1))
					builder.append(" and t.teacherId=" + obj);
				else
					builder.append(" and t is null");
			if (null != (obj = courseManage.getTclass().getClassId()))
				if (!obj.equals(-1))
					builder.append(" and tc.classId=" + obj);
				else
					builder.append(" and tc is null");

			if (null != (obj = courseManage.getCourseTimeSet()))
				builder.append(" and cmg.courseTimeSet=" + obj);
			if (null != (obj = courseManage.getCredit()))
				builder.append(" and cmg.credit=" + obj);
			if (null != (obj = courseManage.getWeeks()) && "".equals(obj))
				builder.append(" and cmg.weeks='" + obj + "'");
			if (null != (obj = courseManage.getCourseType()))
				builder.append(" and courseType=" + obj);
		}
		return getCourseManageDao()
				.findCourseManageListByHQL(builder.toString());
	}

	@Override
	public void removeAllCourseManage(int[] ids) {
		getCourseManageDao().deleteCourseManageEtys(ids);
		// TODO Auto-generated method stub
	}

	// 课程安排表导出方法
	private ByteArrayOutputStream exportToExcel(List list, String[] colName) {

		XSSFWorkbook workbook = new XSSFWorkbook();
		XSSFSheet sheet = workbook.createSheet("sheet1");
		XSSFRow row = sheet.createRow(0); // 创建一行
		// 标题创建
		for (short i = 0; i < colName.length; i++)
			row.createCell(i).setCellValue(new XSSFRichTextString(colName[i]));

		Iterator<CmgTemp> it = list.iterator();
		int index = 0;
		while (it.hasNext()) {
			index++;
			row = sheet.createRow(index);
			CmgTemp cmg = it.next();
			row.createCell(0).setCellValue(cmg.getCourseName());
			// 临时存储数据
			int temp = cmg.getCourseTimeSet();
			row.createCell(1).setCellValue(temp == 0
					? "上午第一大节"
					: temp == 1 ? "下午第一大节" : temp == 2 ? "上午第二大节" : "下午第二大节");
			row.createCell(2).setCellValue(cmg.getWeeks());
			temp = cmg.getCourseType();
			row.createCell(3).setCellValue(
					temp == 0 ? "公共必修课" : temp == 1 ? "非限制性选修课" : "限制性选修课");
			row.createCell(4).setCellValue(cmg.getCredit());
			row.createCell(5).setCellValue(cmg.getClassName());
			row.createCell(6).setCellValue(cmg.getTeacherName());
			row.createCell(7).setCellValue(cmg.getAddressName());

		}
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		try {
			workbook.write(os);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return os;
	}
	@Override
	public Map getParam() {
		Map<String, List> connMap = new HashMap<String, List>();
		// 教师 /班级、课程、地址
		connMap.put("t", getTeacherDao()
				.findTeacherBySql("select teacherId,teacherName from Teacher"));
		connMap.put("adr", getAddressDao()
				.findAdrBySQL("select addressId,addressName from Address"));
		connMap.put("c", getCourseDao().findCourseNameAndId());
		connMap.put("cl", getClassDao().findClassNameAndId());
		return connMap;
	}
}
